# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: jaewon

import json
from typing import List, Optional

from coin.exchange.base.order_gateway import OrderSide
from coin.exchange.okex.ws.trade_base import OkexTradeClientBase


class OkexSpotTradeClient(OkexTradeClientBase):
  def __init__(self, api_key: str, secret_key: str, symbol_list: Optional[List[str]], logger=None):
    super().__init__(api_key, secret_key, symbol_list=symbol_list, logger=logger)
    self._ws_url = 'wss://real.okex.com:10441/websocket?compress=true'
    for symbol in symbol_list:
      self._channels.append('ok_sub_spot_%s_order' % symbol)
      self._channels.append('ok_sub_spot_%s_balance' % symbol)

  def order(self, symbol: str, order_side: OrderSide, price: float, qty: float):
    if order_side == OrderSide.BUY:
      okex_order_type = 'buy'
    elif order_side == OrderSide.SELL:
      okex_order_type = 'sell'
    else:
      raise ValueError()

    param = {
        'api_key': self._api_key,
        'symbol': symbol,
        'price': '%.8f' % price,
        'amount': '%.8f' % qty,
        'type': okex_order_type
    }
    param['sign'] = self._sign(param)
    return self._ws.write_message(
        json.dumps({
            'event': 'addChannel', 'channel': 'ok_spot_order', 'parameters': param
        }))

  def cancel(self, symbol: str, order_id: str):
    param = {'api_key': self._api_key, 'symbol': symbol, 'order_id': order_id}
    param['sign'] = self._sign(param)
    return self._ws.write_message(
        json.dumps({
            'event': 'addChannel', 'channel': 'ok_spot_cancel_order', 'parameters': param
        }))

  def orderinfo(self, symbol: str, order_id: str):
    param = {'api_key': self._api_key, 'symbol': symbol, 'order_id': order_id}
    param['sign'] = self._sign(param)
    return self._ws.write_message(
        json.dumps({
            'event': 'addChannel', 'channel': 'ok_spot_orderinfo', 'parameters': param
        }))

  def user_info(self):
    param = {'api_key': self._api_key}
    param['sign'] = self._sign(param)
    return self._ws.write_message(
        json.dumps({
            'event': 'addChannel', 'channel': 'ok_spot_userinfo', 'parameters': param
        }))
